<template>
  <div class="app-container">
    <el-header>
        <span
          style="display: block; width: 100%; height: 30px; background: #001529; text-align: center; font-size: 20px; font-weight: bold; color: white">
          文章数据
        </span>
    </el-header>
    <el-main>
      <!--查询-->
      <el-form v-show="showSearch" :inline="true" ref="form" :model="params" label-width="68px">
        <el-form-item label="标题">
          <el-input size="mini" v-model="params.title" clearable placeholder="请输入标题"
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!--文章列表增删改查-->
      <el-card style="width: 100%">
        <div style="float: right">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="add = true">新增</el-button>
            </el-col>
          </el-row>

          <el-dialog title="新增" :visible.sync="add">
            <el-form :model="newArticle" :rules="rulesArticle" ref="form">
              <el-form-item label="文章标题" :label-width="formLabelWidth" prop="title">
                <el-input v-model="newArticle.title" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="文章内容" :label-width="formLabelWidth" prop="content">
                <el-input type="textarea" v-model="newArticle.content" autocomplete="off"></el-input>
              </el-form-item>
              <el-form :model="user">
                <el-form-item label="创建人" :label-width="formLabelWidth" prop="content">
                  <el-input v-model="user.nickname" autocomplete="off" disabled></el-input>
                </el-form-item>
              </el-form>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="add = false">取 消</el-button>
              <el-button type="primary" @click="handleAdd">确 定</el-button>
            </div>
          </el-dialog>

          <el-dialog title="编辑" :visible.sync="update">
            <el-form :model="oldArticle" :rules="rulesArticle" ref="form">
              <el-form-item label="标题" :label-width="formLabelWidth">
                <el-input v-model="oldArticle.title" autocomplete="off"></el-input>
              </el-form-item>

              <el-form-item label="内容" :label-width="formLabelWidth">
                <el-input :rows="16" type="textarea" v-model="oldArticle.content" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="update = false">取 消</el-button>
              <el-button type="primary" @click="handleUpdate">确 定</el-button>
            </div>
          </el-dialog>

          <el-dialog title="查看" :visible.sync="show">
            <el-form :model="article" :rules="rulesArticle" ref="form">
              <el-form-item label="文章内容" :label-width="formLabelWidth" prop="content">
                <el-input :rows="18" type="textarea" v-model="article.content" autocomplete="on" disabled></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="show = false">确 定</el-button>
            </div>
          </el-dialog>
        </div>


        <el-table :data="tableData"
                  style="font-weight: bold;border: #001529;"
                  border
                  v-loading="loading"
        >
          <el-table-column label="ID" prop="id" align="center" width="50px"></el-table-column>
          <el-table-column label="标题" prop="title" align="center" width="200px"></el-table-column>
          <el-table-column label="内容" align="center">
            <template slot-scope="scope">
              <el-button @click="showContent(scope.row)" size="small" type="info" plain>点击查看</el-button>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" width="200px">
            <template slot-scope="scope">{{ new Date(scope.row.createTime).toLocaleString('zh-CN',{ timeZone: 'Asia/Shanghai', hour12: false })}}</template>
          </el-table-column>
          <el-table-column label="创建人" prop="nickname" align="center" width="100px"></el-table-column>
          <el-table-column label="操作" align="center" width="80px">
            <template slot-scope="scope">
              <div>
                <el-button size="mini" type="danger" @click="delById(scope.row)" plain
                           v-if="user.role === '管理员'">删除
                </el-button>
              </div>

              <el-button type="primary"
                         size="mini"
                         @click="updateById(scope.row)"
                         plain>编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <template>
          <div class="block">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="pageBlogReq.pageNum"
              :page-size="pageBlogReq.pageSize"
              layout="total, prev, pager, next"
              :total="total">
            </el-pagination>
          </div>
        </template>
      </el-card>
    </el-main>


  </div>
</template>

<script>
export default {
  data() {
    return {
      user: JSON.parse(sessionStorage.getItem('user-key' || '{}')),
      showSearch: true,
      params: {
        title: ''
      },
      add: false,
      update: false,
      show: false,
      formLabelWidth: '150px',
      newArticle: {
        title: '',
        content: '',
        createUser: ''
      },
      rulesArticle: {
        title: [
          {
            required: true,
            message: '请输入标题',
            trigger: 'blur'
          }
        ],
        content: [
          {
            required: true,
            message: '请输入内容',
            trigger: 'blur'
          }
        ]
      },
      tableData: [],
      article: {
        content: ''
      },
      loading: true,
      pageBlogReq: {
        pageNum: 1,
        pageSize: 3,
        createUser: ''
      },
      total: 0,
      oldArticle: {
        id: '',
        title: '',
        content: '',
      }
    }
  },
  mounted() {//页面加载后触发
    this.fetchData()
  },
  methods: {
    handleQuery() {
      this.$request.get('blogs/queryTitle', {params: {title: this.params.title}}).then(res => {
        if (res.code === 200) {
          this.$message.success("请求成功")
          this.loading = false
          this.tableData = res.data.blogs
          this.total = res.data.total
        } else {
          this.$message.error("没有找到匹配的数据")
          this.fetchData()
        }
      }).catch(() => {
        this.$message.error("系统错误")
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.params.title = ''
      this.fetchData()
    },
    handleAdd() {
      this.newArticle.createUser = this.user.id
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$request.post('/blogs/addBlogs', this.newArticle).then(res => {
            if (res.code === 200) {
              //成功添加
              this.fetchData()
              this.add = false
            } else {
              this.$message.error(res.msg)
            }
          }).catch(() => {
            this.$message.error("系统错误")
          })
        }
      })
    },
    handleUpdate() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$request.put('/blogs/updateArticle', this.oldArticle).then(res => {
            if (res.code === 200) {
              //成功更新
              this.$message.success('更新成功')
              this.fetchData()
            } else {
              this.$message.error(res.msg)
            }
          }).catch(() => {
            this.$message.error("系统错误")
          })
        }
      })
    },
    updateById(row) {
      this.update = true
      this.oldArticle.id = row.id
      this.oldArticle.title = row.title
      this.oldArticle.content = row.content
    },
    delById(row) {
      this.$request.delete('/blogs/deleteById', {params: {id: row.id}}).then(res => {
        if (res.code === 200) {
          this.$message.success("删除成功")
          this.fetchData()
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => {
        this.$message.error("系统错误")
      })
    },
    fetchData() {
      this.pageBlogReq.createUser = this.user.id
      this.$request.post('/blogs/queryBlogs', this.pageBlogReq).then(res => {
        if (res.code === 200) {
          this.loading = false
          this.tableData = res.data.blogs
          this.pageBlogReq.pageNum = res.data.pageNum
          this.pageBlogReq.pageSize = res.data.pageSize
          this.total = res.data.total
        }else {
          this.$message.error(res.msg)
        }
      }).catch(() => {
        this.loading = false;
        this.$message.error("系统错误")
      })
    },
    handleSizeChange(val) {
      this.pageBlogReq.pageSize = val;
      this.fetchData(); // 当每页显示条数改变时，重新获取数据
    },
    handleCurrentChange(val) {
      this.pageBlogReq.pageNum = val;
      this.fetchData(); // 当每页显示条数改变时，重新获取数据
    },
    showContent(row) {
      this.show = true
      this.$request.get(`/blogs/${row.id}`).then(res => {
        if (res.code === 200) {
          this.article.content = res.data.blogs[0].content
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => {
        this.$message.error("系统错误")
      })
    },
  }
}
</script>

<style scoped>
.app-container {
  font-size: 26px;
  font-weight: bold;
  padding: 20px;
}
</style>
